<?php
    
	define('basepath', realpath("../") . '/');
	
	switch ($_GET['fn']) {
	
		case 'loadpage':
			loadpage();
			break;
		
		case 'loadpages':
			loadpages();
			break;
		
		case 'save':
			save();
			break;
			
		case 'deletepage':
			deletepage();
			break;
	
	}
	
	
	function loadpage() {
		
		$filename = $_POST['site'] == '' ? 'index' : $_POST['site'];
		
		if ( is_file( basepath . 'pages/' . $filename . '.json') ) {
			$content = file_get_contents( basepath . 'pages/' . $filename . '.json');
		} else {
			$content = '';
		}
		
		echo $content;
		
	}
	
	function loadpages() {
		
		$pages = scandir(basepath . 'pages');
		echo '{"pages":[';
		
		foreach ( $pages as $page ) {
			if ($page[0] !== '.' ) {
				$page = explode('.', $page );
				echo '"' . $page[0] . '", ';
			}
		}
		
		echo ']}';
		
	}
	
	function save() {
		
		$content = str_replace('\"', '"', $_POST['data']);
		
		$content = preg_replace('/[\\\]+/', '\\', $content);
		$content = preg_replace('/^[aeiou]+$/', '', $content); 
		
		$filename = $_POST['site'] == '' ? 'index' : $_POST['site'];
		
		$file = fopen( basepath . 'pages/' . $filename . '.json', "w");
		fwrite($file, $content);
		fclose($file);
		
		echo $content;
		
	}
	
	function deletepage() {
		
		$filename = $_POST['site'];
		
		if ( is_file( basepath . 'pages/' . $filename . '.json') ) {
			unlink(basepath . 'pages/' . $filename . '.json');
		}

	}
	
	
	
?>
